const _ = require('lodash');
/* 充电桩应答中心合法用户认证通过信息命令*/
exports.run = (info, core, socket, logger) => {
  if (!socket.charging) { return; }
  let redis = core.getService('redis').getClient();
  const reader = new core.BufferReader(info.data),
    userIdBuf = reader.read(2),
    cmdIndexBuf = reader.read(2),
    chargingGunCount = reader.read(1);
  const Charging = core.getModel('Charging');
  let data = {
    chargingGunCount: chargingGunCount.readUInt8(),
    chargingGuns: [],
    accessed_at: _.now(),
  };
  _.times(data.chargingGunCount, () => {
    let type = reader.read(1),
        chargeKwh = reader.read(2),
        chargeAh = reader.read(2),
        chargingTime = reader.read(2),
        startSoc = reader.read(1),
        nowSoc = reader.read(1),
        degreeKwh = reader.read(4);
    data.chargingGuns.push({
      type: (() => {
        switch(type.readUInt8()) {
          case 1: return '直流';
          case 2: return '交流';
          default: return '';
        }
      })(),
      chargeKwh: chargeKwh.readUInt16LE() * 0.01,
      chargeAh: chargeAh.readUInt16LE() * 0.1,
      chargingTime: chargingTime.readUInt16LE(),
      startSoc: startSoc.readUInt8(),
      nowSoc: nowSoc.readUInt8(),
      degreeKwh: degreeKwh.readUInt32LE() * 0.01,
    });
  });
  // 判断余额
  const charging = socket.charging;
  Charging.savePacket(charging, '0x39', data).then(() => {
    // redis.get(`currentChargingOrder:${charging}`, (err, info) => {
      // info = info ? JSON.parse(info): null;
      // if (info) {
        // 调用 接口判断余额是否
        core.getService('sdk')
          .checkBalance(charging)
          .then((response) => {
            logger.info(response)
          })
          .catch((err) => logger.error(err));
        // 50s 超时提示
        redis.setex(`monitor:${charging}`, [50, true]);
      // }
    // })
  });
}

